import { useContext, useEffect } from 'react';
import { ContractManageAPI } from '../common/type';
import { Col, Empty, Row, Space, Spin, Timeline, Tooltip, message } from 'antd';
import { getMcontractProcessService } from '../services';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { ConractControllerContext } from '../common';
import { UpCircleOutlined, DownCircleOutlined } from '@ant-design/icons';
import MyIcon from '@/components/MyIcon';
import { newGetFileNameNotType } from '@/utils';
import { getBaseUrl } from '@/services/urlconst';
import { payTypeStr } from '../mconfig';

export const DetailInfoViewTabsPayment: React.FC<ContractManageAPI.IDetailInfoViewTabsPayment> = ({
  tabsPaneInfoObj,
  allOpenChildren,
  changeOpenChildren,
  clickOpenClose,
}) => {
  /**引入上下文 */
  const { styleFixCls } = useContext(ConractControllerContext);

  /** 获取数据回调 */
  const processCallback = (res: any) => {
    if (res && res?.msgFlag) {
      if (res?.obj?.length > 0 && allOpenChildren?.openIdKey?.length == 0) {
        const allOpenIDList: string[] = res?.obj?.map((item: any) => item?.id);
        const changeOpenObj = {
          allOpenKeys: allOpenIDList,
          openIdKey: [allOpenIDList?.[0]],
        };
        changeOpenChildren(changeOpenObj);
      }
    } else {
      message.error(res?.message);
    }
  };

  /** 引入获取数据接口 */
  const { getMcontractProcessData, getMcontractProcessLoading, getMcontractProcessRun } = getMcontractProcessService(processCallback);

  /** 数据初始化 */
  useEffect(() => {
    if (tabsPaneInfoObj?.tabKeyType == 'agreePane') {
      getMcontractProcessRun({
        contractCode: tabsPaneInfoObj?.tabKeyId,
      });
    }
  }, [tabsPaneInfoObj]);

  /** 处理发票路径 */
  const handPayURLWord = (wordUrl: string) => {
    const wordUrlList: string[] = wordUrl?.split(',');
    let fieldInfoList: Record<string, any>[] = [];
    wordUrlList?.forEach((item: any) => {
      if (item) {
        const nameStrList: string[] = item?.split('&'); //分割文件路劲
        const fieldName: string | any = nameStrList?.find((nameItem: any) => nameItem?.includes('filename=')); //获取文件名称
        if (fieldName) {
          const wordName: string = fieldName?.replace('filename=', '');
          fieldInfoList?.push({
            downFieldUrl: `${getBaseUrl()}${item}`,
            fieldWordName: wordName,
          });
        }
      }
    });
    return fieldInfoList;
  };

  return (
    <Spin spinning={getMcontractProcessLoading}>
      <div className="commonTabsBodyDom">
        <div className={'tabsBodyInfoDom'}>
          {getMcontractProcessData?.length > 0 ? (
            <ScrollBarLayout style={{ padding: '5px 20px' }}>
              <div className={styleFixCls + 'contractTimeLineSty'}>
                <Timeline>
                  {getMcontractProcessData?.map((item: any, index: number) => {
                    // const textURL = `/wechat/U8AppProxy?gnid=bxdsh&id=fj&gsdm=001&kjnd=2023&djbh=2023130582&annexid=176&filename=pdficon.jpg,/wechat/U8AppProxy?gnid=bxdsh&id=fj&gsdm=001&kjnd=2023&djbh=2023130582&annexid=176&filename=pdficon.jpg,/wechat/U8AppProxy?gnid=bxdsh&id=fj&gsdm=001&kjnd=2023&djbh=2023130582&annexid=176&filename=pdficon.jpg`
                    const fieldList: Record<string, any>[] = item?.payURL ? handPayURLWord(item?.payURL) : [];
                    // const fieldList: Record<string, any>[] = textURL ? handPayURLWord(textURL) : []

                    return (
                      <Timeline.Item
                        key={`${item?.id}-${index}`}
                        dot={allOpenChildren?.openIdKey?.includes(item?.id) ? <MyIcon style={{ fontSize: 18 }} type="icon-time-circle" /> : null}
                      >
                        <div style={{ margin: '5px 0px' }}>
                          【<span className={styleFixCls + 'contractTimeLineSty-titleTimeBoxSty'}>{payTypeStr(item.payType) || '--'}</span>
                          】款项于&nbsp;
                          <span className={styleFixCls + 'contractTimeLineSty-titleTimeBoxSty'}>{item?.payTime || '--'}</span>
                          &nbsp;收支，收支情况如下：
                          <a
                            onClick={() => {
                              clickOpenClose(item?.id, allOpenChildren, changeOpenChildren);
                            }}
                          >
                            {allOpenChildren?.openIdKey?.includes(item?.id) ? <UpCircleOutlined /> : <DownCircleOutlined />}
                          </a>
                        </div>
                        {allOpenChildren?.openIdKey?.includes(item?.id) && (
                          <div className={`${styleFixCls}contractTimeLineSty-agreeBodyBox`} style={{ padding: '10px' }}>
                            <Row gutter={[12, 8]} className={`${styleFixCls}contractTimeLineSty-agreeBodyBox-rowBox`}>
                              {/* <Col span={12}>
                                <dt>
                                  资金流向
                                </dt>：
                                <dd>{payCapitalDirStr(item?.capitalDir)}</dd>
                              </Col>
                              <Col span={12}>
                                <dt>
                                  付款单号
                                </dt>：
                                <dd>{item?.payOrderNum || '--'}</dd>
                              </Col> */}

                              {/* <Col span={12}>
                                <dt>
                                  合同编号
                                </dt>：
                                <dd>{item?.contractCode || '--'}</dd>
                              </Col> */}

                              <Col span={12}>
                                <dt>合同金额</dt>：
                                <dd>
                                  <span style={{ fontWeight: 700, color: '#000' }}>{item?.sumInTax ? `${item?.sumInTax}.00` : '0.00'}</span>
                                  &nbsp;元
                                </dd>
                              </Col>

                              <Col span={12}>
                                <dt>已付金额</dt>：
                                <dd>
                                  <span style={{ fontWeight: 700, color: '#ff4d4f' }}>{item?.sumPaid ? `${item?.sumPaid}.00` : '0.00'}</span>
                                  &nbsp;元
                                </dd>
                              </Col>
                              <Col span={12}>
                                <dt>本次支付</dt>：
                                <dd>
                                  <span style={{ fontWeight: 700, color: '#096dd9' }}>{item?.sumThisPaid ? `${item?.sumThisPaid}.00` : '0.00'}</span>
                                  &nbsp;元
                                </dd>
                              </Col>

                              <Col span={12}>
                                <dt>收款码</dt>：<dd>{item?.payCode || '--'}</dd>
                              </Col>

                              <Col span={24}>
                                <dt>发票信息</dt>：
                                <dd>
                                  {item?.payURL ? (
                                    <Space wrap size={[0, 6]}>
                                      {fieldList?.map((item: any, index: number) => {
                                        return (
                                          <span key={`${index}-word-payURL`}>
                                            <Tooltip title={item?.fieldWordName}>
                                              <a
                                                onClick={() => {
                                                  message.success('下载中，请稍后...');
                                                  const iframe: any = document.createElement('iframe');
                                                  iframe.style.display = 'none'; // 防止影响页面
                                                  iframe.style.height = 0; // 防止影响页面
                                                  iframe.src = item?.downFieldUrl;
                                                  document.body.appendChild(iframe);
                                                }}
                                              >
                                                <MyIcon type="icon-file-text-fill" />
                                                &nbsp;
                                                {newGetFileNameNotType(item?.fieldWordName, 7)}
                                              </a>
                                              {fieldList?.length - 1 == index ? '' : '，'}
                                            </Tooltip>
                                          </span>
                                        );
                                      })}
                                    </Space>
                                  ) : (
                                    '--'
                                  )}
                                </dd>
                              </Col>

                              <Col span={24}>
                                <dt>付款事由</dt>：<dd>{item?.payReason || '--'}</dd>
                              </Col>

                              {/* <a href='http://222.186.101.212:9301/hrky/file/contract/info/2023/10/28/161245277/科研设备采购合同（详版）.docx'>下载</a>
                              &nbsp;
                              <a
                                onClick={() => {
                                  window.open("http://222.186.101.212:9301/hrky/file/contract/info/2023/10/28/161245277/科研设备采购合同（详版）.docx")
                                }}
                              >下载</a>

                              &nbsp;
                              <a
                                onClick={() => {
                                  message.success("下载中，请稍后...")
                                  const iframe: any = document.createElement("iframe");
                                  iframe.style.display = "none"; // 防止影响页面
                                  iframe.style.height = 0; // 防止影响页面
                                  iframe.src = "http://222.186.101.212:9301/hrky/file/contract/info/2023/10/28/161245277/科研设备采购合同（详版）.docx";
                                  document.body.appendChild(iframe);
                                }}
                              >
                                下载
                              </a> */}
                            </Row>
                          </div>
                        )}
                      </Timeline.Item>
                    );
                  })}
                </Timeline>
              </div>
            </ScrollBarLayout>
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
          )}
        </div>
      </div>
    </Spin>
  );
};
